import { createRouter, createWebHashHistory } from 'vue-router'
import Login from './views/Login.vue'
import DataCollection from './components/DataCollection.vue'
import DataManagement from './components/DataManagement.vue'
import TaskManagement from './components/TaskManagement.vue'
import SystemSettings from './components/SystemSettings.vue'
import DataDetail from './views/DataDetail.vue'
import TaskDetail from './views/TaskDetail.vue'
import AdminManagement from "./components/AdminManagement.vue";
import TaskTypeManagement from "./components/TaskTypeManagement.vue";
import UdpMonitor from "./components/UdpMonitor.vue";
import { ElMessageBox } from 'element-plus';




// 动态确定默认路由的重定向目标
const getDefaultRedirectPath = () => {
  const currentUserIdentity = localStorage.getItem('currentUserIdentity');
  // 管理员默认重定向到数据采集，非管理员默认重定向到数据管理
  return currentUserIdentity === '1' ? '/data-collection' : '/data-management';
};

const routes = [
  { path: '/', redirect: (to) => {
    return { path: getDefaultRedirectPath() }
  } },
  // 保存原始默认路由作为备用
  { path: '/default-redirect', redirect: '/data-collection' },
  { path: '/login',name: 'Login',  component: Login, meta: { requiresAuth: false } },
  { path: '/data-collection', component: DataCollection, meta: { requiresAuth: true, confirmLeave: true } },
  { path: '/data-management', component: DataManagement, meta: { requiresAuth: true } },
  { path: '/task-management', component: TaskManagement, meta: { requiresAuth: true } },
  { path: '/system-settings', component: SystemSettings, meta: { requiresAuth: true } },
  { path: '/admin-management', component: AdminManagement, meta: { requiresAuth: true } },
  { path: '/taskType-management', component: TaskTypeManagement, meta: { requiresAuth: true } },

  { path: '/data-management/detail/:id', name: 'DataDetail', component: DataDetail, meta: { requiresAuth: true } },
  { path: '/task-management/detail/:id', name: 'TaskDetail', component: TaskDetail , meta: { requiresAuth: true } },
  { path: '/admin-management/detail/:id', name: 'TaskDetail', component: TaskDetail , meta: { requiresAuth: true } },
  { path: '/taskType-management/detail/:id', name: 'TaskDetail', component: TaskDetail , meta: { requiresAuth: true } },
  { path: '/udp-monitor', component: UdpMonitor },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})


// 全局变量用于存储当前采集状态
window.dataCollectionStatus = '待机';

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true'

  // 检查是否需要离开确认（当从需要确认的页面离开且正在采集时）
  if (from.meta.confirmLeave && window.dataCollectionStatus === '采集中') {
    console.log('检测到正在从数据采集页面离开，当前状态：采集中');
    
    // 使用同步的window.confirm确保在导航守卫中正常工作
    if (window.confirm('当前正在进行采集任务，是否停止采集并离开？')) {
      console.log('用户确认离开，执行导航');
      // 这里无法直接调用组件内的stopCollection函数
      // 但当用户确认离开后，我们允许导航
      // 组件的onUnmounted钩子会处理清理工作
      next();
    } else {
      console.log('用户取消离开');
      // 用户取消导航
      next(false);
      return;
    }
  } else {
    // 记录非采集状态下的导航
    if (from.meta.confirmLeave && window.dataCollectionStatus !== '采集中') {
      console.log('从数据采集页面离开，当前状态：' + window.dataCollectionStatus + '，无需确认');
    }
  }

  if (to.meta.requiresAuth && !isAuthenticated) {
    // 如果需要认证且未登录，重定向到登录页面
    next('/login')
  } else if (to.path === '/login' && isAuthenticated) {
    // 如果已登录但访问登录页，重定向到首页
    next('/')
  } else if (isAuthenticated && to.path === '/data-collection') {
    // 权限控制：只有管理员（身份为1）才能访问数据采集页面
    const currentUserIdentity = localStorage.getItem('currentUserIdentity');
    if (currentUserIdentity !== '1') {
      // 非管理员重定向到数据管理页面
      ElMessageBox.alert('您没有权限访问此页面', '权限不足', {
        confirmButtonText: '确定'
      });
      next('/data-management');
      return;
    }
    next();
  } else {
    next()
  }
})


export default router
